/**
 * 泛娱区块链 - BindingPhone
 * https://menger.me
 * @author: zaric
 * @creation time: 2018-12-11
 */


'use strict';
import React, {Component} from 'react';
import {
    KeyboardAvoidingView,
    KeyboardAvoidingViewComponent,
    StyleSheet,
    TextInput,
    TouchableOpacity,
    View
} from 'react-native';
import Images from '../../asset';
import {Badge} from 'teaset';
import PropTypes from 'prop-types';
import Button from '../../component/common/Button';
import ServicesApi from '../../config/ServicesApi';
import ActionsManager from '../../config/manager/ActionsManager'
import ImageView from './ImageView';
import {inject, observer} from "mobx-react";

export default class CommentView extends Component {

    static propTypes = {
        ...View.propTypes,
        count: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
        topic_id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
        create_user: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    };

    static defaultProps = {
        count: 0,
        information: {},
        collect_state: 0,
        reply_module: 'information',
        onCallBack: () => {},
    };

    constructor(props) {
        super(props);
        this.state = {
            showRightButton: false,
            count: props.count,
            collect_state: props.collect_state,
        };
        this.inputData = {
            comment: '',
        }
    }

    componentDidMount() {
        // console.log('componentDidMount---->', this.props);
    }

    componentWillReceiveProps(nextProps){
        // console.log('componentWillReceiveProps---->', nextProps);
        if (nextProps.collect_state !== this.state.collect_state) {
            this.setState({
                count: nextProps.count,
                collect_state: nextProps.collect_state,
            })
        }
    }

    componentWillUnmount() {
        // this.keyboardDidShowListener.remove();
        // this.keyboardDidHideListener.remove();
    }

    _onBlur = () => {
        this.setState({showRightButton: false})
    };

    _onFocus = () => {
        this.setState({showRightButton: true})
    };
    //点击评论
    _onPressComment = () => {
        const {topic_id, onCallBack} = this.props;
        RouterHelper.navigate('评论', 'CommentList', {topic_id, reply_module: 'information', onCallBack: () => onCallBack()});
    };

    //点击分享
    _onPressShare = async () => {
        const {taskStore, topic_id, article_type, title} = this.props;
        // let url = '';
        // if (article_type === '1') { //文章
        //     url = `${ServicesApi.SHARE_ARTICLE_URL}?id=${topic_id}`
        // } else { //视频
        //     url = `${ServicesApi.SHARE_VIDEO_URL}?id=${topic_id}`
        // }
        ActionsManager.showShareModule({
            type: 'link',
            title: title,
            text: title,
            url: ServicesApi.DOWNLOAD_HOST,
            imageUrl: ServicesApi.ICON_APP,
        });

        await taskStore.saveTask('news_share')
    };

    //点击收藏
    _onPressCollection = async () => {
        // console.log('收藏');
        let {collect_state} = this.state;
        let {topic_id, information, onCallBack} = this.props;
        let url;
        if (collect_state) { //已收藏，点击取消收藏
            url = ServicesApi.COLLECT_DEL;
            const data = {
                collect_id: information.collect_id,
                create_user: global.secretKey,
                // information_id: topic_id,
            };
            const result = await Services.post(url, data);
            if (result.code === StatusCode.SUCCESS_CODE) {
                onCallBack();
                ToastManager.show('取消收藏成功!');
                this.setState({collect_state: 0});
            } else {
                ToastManager.show(result.dec || 'error')
            }
        } else { //未收藏，点击收藏
            url = ServicesApi.COLLECT_SAVE;
            const data = {
                create_user: global.secretKey,
                information_id: topic_id,
            };
            const result = await Services.post(url, data);
            if (result.code === StatusCode.SUCCESS_CODE) {
                onCallBack();
                ToastManager.show('收藏成功!');
                this.setState({collect_state: result.data.collect_id});
            } else {
                ToastManager.show(result.dec || 'error')
            }
        }
    };

    //发送评论
    _onPressSend = () => {
        let params = {
            title: '温馨提示',
            detail: '',
            actions: [
                {
                    title: '确定', onPress: () => {
                        AlertManager.hide()
                    }
                }
            ]
        };
        let reply_content = this.inputData['comment'];
        if (!reply_content) {
            params['detail'] = '请输入评论内容';
            AlertManager.show(params)
        } else {
            this.requestComment(reply_content);
        }
    };

    requestComment = async (reply_content) => {
        const {topic_id, reply_module, taskStore} = this.props;
        let url = ServicesApi.REPLY_SAVE;
        let data = {
            topic_id,
            reply_module,
            reply_content,
            create_user: global.secretKey,
            reply_type: 'topic'
        };
        const result = await Services.post(url, data);
        if (result.code === 0) {
            ToastManager.show('评论成功');
            this.inputRef.clear();
            this.inputRef.blur();
            this.inputData['comment'] = '';
            let tempCount = parseFloat(this.state.count);
            tempCount++;
            this.setState({count: tempCount});
            await taskStore.saveTask('topic');
            this._onPressComment();
        }
    };

    _onChangeText = (key, text) => {
        this.inputData[key] = text
    };

    _renderRightView = (showRightButton, collect_state, count) => {
        // console.log('collect_state---->', collect_state);
        if (showRightButton) {
            return (<Button style={styles.button} title='发送' onPress={this._onPressSend}/>)
        } else {
            return (
                <View style={styles.rightContainer}>
                    <TouchableOpacity
                        style={styles.badgeCont}
                        onPress={this._onPressComment}
                    >
                        <ImageView
                            style={styles.comment}
                            source={Images.icon_comment_msg}
                        />
                        <Badge
                            maxCount={99}
                            type={'square'}
                            countStyle={styles.countStyle}
                            count={count}
                            style={styles.badge}
                        />
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.cusMargin} onPress={this._onPressCollection}>
                        <ImageView
                            style={styles.collection}
                            source={parseInt(collect_state) > 0 ? Images.icon_have_collect : Images.icon_collection}
                        />
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.cusMargin} onPress={this._onPressShare}>
                        <ImageView style={styles.share} source={Images.icon_video_share}/>
                    </TouchableOpacity>
                </View>
            )
        }
    };

    render() {
        let {showRightButton, collect_state} = this.state;
        let {count} = this.props;
        // console.log('this.props---->', this.props);
        return (
            <KeyboardAvoidingView behavior={__IOS__ ? 'position' : 'height'}>
                <View style={styles.bottomInfo}>
                    <TextInput
                        style={styles.commentInput}
                        placeholder={'说说你的看法...'}
                        ref={(v) => this.inputRef = v}
                        onChangeText={(text) => this._onChangeText('comment', text)}
                        onBlur={this._onBlur}
                        onFocus={this._onFocus}
                    />
                    {this._renderRightView(showRightButton, collect_state, count)}
                </View>
            </KeyboardAvoidingView>
        );
    }
}

const styles = StyleSheet.create({
    bottomInfo: {
        width: '100%',
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 15,
        paddingVertical: 7,
        borderTopWidth: StyleSheet.hairlineWidth,
        borderTopColor: '#dbdbdb',
        backgroundColor: '#fff',
    },
    rightContainer: {
        paddingVertical: 8,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    countStyle: {
        fontSize: FontSize(7),
        color: '#fff',
    },
    cusMargin: {
        marginLeft: 10
    },
    badgeCont: {
        // flexDirection: 'row',
        // backgroundColor: '#f00'
    },
    badge: {
        position: 'absolute',
        minWidth: 22,
        borderRadius: 4,
        left: -12,
        top: -8,
        backgroundColor: '#ff7e00',
    },
    comment: {
        width: 18,
        height: 18,
    },
    collection: {
        width: 18,
        height: 18,
    },
    share: {
        width: 18,
        height: 18,
    },
    commentInput: {
        flex: 1,
        height: 35,
        borderRadius: 4,
        marginRight: 35,
        paddingHorizontal: 10,
        paddingVertical: 0,
        fontSize: FontSize(14),
        backgroundColor: "#f0f0f0",
        color: '#333',
    },
    button: {
        paddingHorizontal: 14,
        backgroundColor: '#fdac5d',
        paddingVertical: 5,
    },
});